<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-03-22
 * Time: 12:57
 */

namespace App\Services\Impl;


use App\Services\IStorageService;
use Illuminate\Support\Str;
use Illuminate\Http\File;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

class QiniuStorageServiceImpl implements IStorageService
{
    /**
     * 是否按日期划分文件夹
     */
    private $daily = true;

    private $directory = '/';

    private $unknown_extension = 'unk';

    private $bucket = 'lebang';

    private $token;

    private $uploadMgr;

    private $bucketMgr;

    const source_domain = 'http://on7uwttp2.bkt.clouddn.com/';

//    const cdn_domain = 'http://lebang-1251165887.file.myqcloud.com/';

    public function __construct()
    {
        if ($this->daily){
            $this->directory .= date('Ymd/');
        }

        require_once(app_path('Libs/QiniuSdk/autoload.php'));

        // 用于签名的公钥和私钥
        $accessKey = config('services.QiniuAccessKey');
        $secretKey = config('services.QiniuSecretKey');
        // 初始化签权对象
        $auth = new Auth($accessKey, $secretKey);

        // 空间名  https://developer.qiniu.io/kodo/manual/concepts
        $bucket = $this->bucket;
        // 生成上传Token
        $this->token = $auth->uploadToken($bucket);
        // 构建 UploadManager 对象
        $this->uploadMgr = new UploadManager();
        //初始化BucketManager
        $this->bucketMgr = new BucketManager($auth);
    }

    public function saveUpload($key)
    {
        $file = request()->file($key);
        if (!$file){
            return false;
        }
        $filename = $file->hashName();
        if (!\File::extension($filename)){
            $filename .= $this->unknown_extension;
        }
        $dstPath = $this->directory.$filename;

        list($ret, $err) = $this->uploadMgr->putFile($this->token, ltrim($dstPath, '/'), $file->getRealPath());
        return $err === null ? $dstPath : false;
    }

    public function saveFile($path)
    {
        $file = new File($path);
        if (!$file->isFile()){
            return false;
        }
        $filename = $file->hashName();
        if (!\File::extension($filename)){
            $filename .= \File::extension($path);
        }
        $dstPath = $this->directory.$filename;

        list($ret, $err) = $this->uploadMgr->putFile($this->token, ltrim($dstPath, '/'), $path);
        return $err === null ? $dstPath : false;
    }

    public function saveStream($binary_stream)
    {
        $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $binary_stream);
        $guesser = ExtensionGuesser::getInstance();
        $extension = $guesser->guess($mime) ? : $this->unknown_extension;
        $dstPath = sprintf('%s%s.%s',$this->directory,Str::random(40),$extension);

        list($ret, $err) = $this->uploadMgr->put($this->token, ltrim($dstPath, '/'), $binary_stream);
        return $err === null ? $dstPath : false;
    }

    public function saveUrl($url)
    {
        $extension = \File::extension($url) ? : $this->unknown_extension;
        $dstPath = sprintf('%s%s.%s',$this->directory,Str::random(40),$extension);

        list($ret, $err) = $this->bucketMgr->fetch($url, $this->bucket, ltrim($dstPath, '/'));
        return $err === null ? $dstPath : false;
    }

    public function getRealPath($path)
    {
        //
    }

    public function getUrl($path)
    {
        if (starts_with($path,'http')){
            return $path;
        }
        return self::source_domain.trim($path,'/');
    }

    public function getUri($path)
    {
        if (starts_with($path,'http')){
            return substr($path,strpos($path,'/',10));
        }
        return '/'.trim($path,'/');
    }

    public function fileExists($path)
    {
        list($ret, $err) = $this->bucketMgr->stat($this->bucket, $path);
        return $err === null;
    }

    public function getContent($path)
    {
    }

    public function getResponse($path)
    {
    }

}